//
//  PlayDetailViewController.m
//  FoodList
//
//  Created by Jason on 16/4/14.
//  Copyright © 2016年 王金晶. All rights reserved.
//

#import "PlayDetailViewController.h"
#import "PlayHeaderView.h"
#import "PlaySectonOneCell.h"
#import "PlaySectionOneOtherCell.h"
#import "RadioMainTableViewCell.h"
#import "PlayHeaderModel.h"
#import "PlaySectionOneModel.h"
#import "PlaySectionTwoModel.h"
#import "PlayerManager.h"
#import "RadioListModel.h"
#import "IntroduceController.h"

@interface PlayDetailViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *playTableView;
@property (nonatomic, strong) PlayHeaderView *headerView;
@property (nonatomic, strong) PlayHeaderModel *headerModel;
@property (nonatomic, strong) PlaySectionOneModel *sectionOneModel;
@property (nonatomic, strong) NSMutableArray *sectionTwoModelArr;
@property (nonatomic, strong) NSTimer *timer;

@end

@implementation PlayDetailViewController

- (NSMutableArray *)sectionTwoModelArr {
    if (_sectionTwoModelArr == nil) {
        _sectionTwoModelArr = [NSMutableArray array];
    }
    return _sectionTwoModelArr;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.playTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithTitle:@"back" style:UIBarButtonItemStylePlain target:self action:@selector(beBack:)];
    self.navigationItem.leftBarButtonItem = barButton;
    
    [self requestDataWithTrackId:_trackId albumId:_albumId trackUid:_trackUid];
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(monitorProgress:) userInfo:nil repeats:YES];
    
}
#pragma mark - 定时器方法 -
- (void)monitorProgress:(NSTimer *)timer {
    self.headerView.playProgress.maximumValue = [[PlayerManager shardedManager] finishTime];
    self.headerView.playProgress.minimumValue = 0;
    NSInteger finishTime = [[PlayerManager shardedManager] finishTime];
    NSInteger currentTime = [[PlayerManager shardedManager] currentTime];
    
    _headerView.currentLab.text = [NSString stringWithFormat:@"%02ld:%02ld", currentTime / 60, currentTime % 60];
    _headerView.finishLab.text = [NSString stringWithFormat:@"%02ld:%02ld", finishTime / 60, finishTime % 60];
    
    
    self.headerView.playProgress.value = [[PlayerManager shardedManager] currentTime];
}
#pragma mark - 返回按钮 -
- (void)beBack:(UIBarButtonItem *)btn {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)requestDataWithTrackId:(NSString *)trackId albumId:(NSString *)albumId trackUid:(NSString *)trackUid {
    [RequestManger requestWithURL:[NSString stringWithFormat:@"http://mobile.ximalaya.com/v1/track/ca/playpage/%@?albumId=%@&device=iPhone&trackUid=%@", trackId, albumId, trackUid] requestType:@"RequestGet" parDic:nil finish:^(NSData *data) {
        NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *userInfoDic = dataDic[@"userInfo"];
        NSDictionary *trackInfoDic = dataDic[@"trackInfo"];
        // 装载表头 model 数据
        self.headerModel = [[PlayHeaderModel alloc] init];
        [_headerModel setValuesForKeysWithDictionary:userInfoDic];
        [_headerModel setValuesForKeysWithDictionary:trackInfoDic];
        // 装载第一个分区 model 数据
        self.sectionOneModel = [[PlaySectionOneModel alloc] init];
        NSDictionary *albumInfoDic = dataDic[@"albumInfo"];
        [_sectionOneModel setValuesForKeysWithDictionary:albumInfoDic];
        NSDictionary *countInfoDic = dataDic[@"countInfo"];
        [_sectionOneModel setValuesForKeysWithDictionary:countInfoDic];
        // 装载第二个分区 model 数组
        NSArray *associationAlbumsInfoAray = dataDic[@"associationAlbumsInfo"];
        for (NSDictionary *dic in associationAlbumsInfoAray) {
            PlaySectionTwoModel *sec2Model = [[PlaySectionTwoModel alloc] init];
            [sec2Model setValuesForKeysWithDictionary:dic];
            [sec2Model setValuesForKeysWithDictionary:countInfoDic];
            [_sectionTwoModelArr addObject:sec2Model];
        }
        // 返回主线程刷新界面
        dispatch_async(dispatch_get_main_queue(), ^{
            self.headerView = [[NSBundle mainBundle] loadNibNamed:@"PlayHeaderView" owner:nil options:nil].firstObject;
            _headerView.headerModel = _headerModel;
            [self.headerView.playBtn addTarget:self action:@selector(playBtnAction:) forControlEvents:UIControlEventTouchUpInside];
            [self.headerView.upBtn addTarget:self action:@selector(upBtnAction:) forControlEvents:UIControlEventTouchUpInside];
            [self.headerView.downBtn addTarget:self action:@selector(downBtnAction:) forControlEvents:UIControlEventTouchUpInside];
            [self.headerView.playProgress addTarget:self action:@selector(playProgressAction:) forControlEvents:UIControlEventValueChanged];
            [self.headerView.playProgress setThumbImage:[UIImage imageNamed:@"slider.png"] forState:UIControlStateNormal];
            [self.headerView.playBtn setImage:[UIImage imageNamed:@"Pause_Radio.png"] forState:UIControlStateNormal];

            self.headerView.frame = CGRectMake(0, 0, Width, 430);
            self.playTableView.tableHeaderView = _headerView;
            [self.playTableView reloadData];
        });
        
    } error:^(NSError *error) {
        NSLog(@"fail");
    }];
}
#pragma  mark - 播放暂停按钮 -
- (void)playBtnAction:(UIButton *)button {
    if ([[PlayerManager shardedManager] isPlaying]) {
        [button setImage:[UIImage imageNamed:@"Play_Radio.png"] forState:UIControlStateNormal];
        [[PlayerManager shardedManager] pause];
    }else {
        [button setImage:[UIImage imageNamed:@"Pause_Radio.png"] forState:UIControlStateNormal];
        [[PlayerManager shardedManager] play];
    }
}
#pragma mark - 上一首按钮 -
- (void)upBtnAction:(UIButton *)button {
    _index --;
    if (_index < 0) {
        _index = _modelArray.count - 1;
    }
    RadioListModel *tempModel = _modelArray[_index];
    [self requestDataWithTrackId:[NSString stringWithFormat:@"%@", tempModel.trackId] albumId:[NSString stringWithFormat:@"%@", tempModel.albumId] trackUid:[NSString stringWithFormat:@"%@", tempModel.uid]];
    [[PlayerManager shardedManager] changeMusicWithIndex:_index];
}
#pragma mark - 下一首按钮 -
- (void)downBtnAction:(UIButton *)button {
    _index ++;
    if (_index > _modelArray.count - 1) {
        _index = 0;
    }
    RadioListModel *tempModel = _modelArray[_index];
    [self requestDataWithTrackId:[NSString stringWithFormat:@"%@", tempModel.trackId] albumId:[NSString stringWithFormat:@"%@", tempModel.albumId] trackUid:[NSString stringWithFormat:@"%@", tempModel.uid]];
    [[PlayerManager shardedManager] changeMusicWithIndex:_index];
}

#pragma mark - 进度条方法 -
- (void)playProgressAction:(UISlider *)slider {
    [[PlayerManager shardedManager] seekToTime:slider.value];
}

#pragma mark - tableView代理方法 -
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 2;
    }else {
        return  self.sectionTwoModelArr.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PlaySectonOneCell *sectionOneCell = [tableView dequeueReusableCellWithIdentifier:@"sectionOneCell"];
    if (sectionOneCell == nil) {
        sectionOneCell = [[NSBundle mainBundle] loadNibNamed:@"PlaySectonOneCell" owner:nil options:nil].firstObject;
    }
    PlaySectionOneOtherCell *otherCell = [tableView dequeueReusableCellWithIdentifier:@"otherCell"];
    if (otherCell == nil) {
        otherCell = [[NSBundle mainBundle] loadNibNamed:@"PlaySectionOneOtherCell" owner:nil options:nil].firstObject;
    }
    RadioMainTableViewCell *sectionTwoCell = [tableView dequeueReusableCellWithIdentifier:@"sectionTwoCell"];
    if (sectionTwoCell == nil) {
        sectionTwoCell = [[NSBundle mainBundle] loadNibNamed:@"RadioMainTableViewCell" owner:nil options:nil].firstObject;
    }
    
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            sectionOneCell.section1Model = _sectionOneModel;
            return sectionOneCell;
        }else {
            otherCell.selectionStyle = UITableViewCellSelectionStyleNone;
            otherCell.model = _sectionOneModel;
            return otherCell;
        }
    }else {
        sectionTwoCell.sec2Model = _sectionTwoModelArr[indexPath.row];
        return sectionTwoCell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        if (_sectionTwoModelArr.count == 0) {
            return 0.01;
        }
        return 50;
    }
    return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return 90;
        }else {
            return 60;
        }
    }else {
        return 80;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        if (_sectionTwoModelArr.count != 0) {
            UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Width, 50)];
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, 100, 20)];
            label.font = [UIFont systemFontOfSize:16];
            label.text = @"相关推荐";
            [myView addSubview:label];
            myView.backgroundColor = [UIColor whiteColor];
            return myView;
        }
        return nil;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && indexPath.row == 1) {
        IntroduceController *introVc = [[IntroduceController alloc] init];
        introVc.tags = _headerModel.tags;
        introVc.intro = _sectionOneModel.intro;
        [self.navigationController pushViewController:introVc animated:YES];
    }else if (indexPath.section == 1) {
        RadioListViewController *listVc = [[RadioListViewController alloc] init];
        PlaySectionTwoModel *tempModel = _sectionTwoModelArr[indexPath.row];
        listVc.myId = tempModel.albumId;
        listVc.uid = tempModel.uid;
        listVc.myTitle = tempModel.title;
        [self.navigationController pushViewController:listVc animated:YES];
    }
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
